/*
 * @Author       : wang chao
 * @Date         : 2023-06-26 18:44:53
 * @LastEditors  : wang chao
 * @LastEditTime : 2023-10-11 14:11:45
 * @FilePath     : dev_rtu_virtualIO.c
 * @Description  :
 * Copyright 2023 BingShan, All Rights Reserved.
 */
#include "stdio.h"
#include "string.h"
#include "board.h"
#include "dev_rtu_mb.h"
#include "dev_rtu_virtualIO.h"

#include "u_data.h"

#define HOLD_REG_MAX 125
static uint16_t hold_regs[HOLD_REG_MAX] = {0};

int dev_rtu_read_hold_regs(uint16_t addr, uint16_t num, uint16_t* buffer)
{
    uint8_t index = 0, base = 0;
    uint16_t io_start = 0, io_end = 0;

    for (index = 0; index < HOLD_REG_MAX; index++)
    {
        // 动态更新参数
        if (index < addr)
        {
            continue;
        }
        if (index > (addr + num))
        {
            break;
        }
        //
        {
            hold_regs[index] = 0;
        }
    }

    if (addr > 124)
    {
        addr = addr - 125;
    }
    index = 0;
    if ((0 <= addr) && (addr < HOLD_REG_MAX))
    {
        io_start = addr;
        if ((addr + num) > (HOLD_REG_MAX))
        {
            io_end = HOLD_REG_MAX;
        }
        else
        {
            io_end = addr + num;
        }
        while (io_start < io_end)
        {
            buffer[index] = hold_regs[io_start];
            io_start++;
            index++;
        }
    }
    return index;
}

int dev_rtu_write_hold_regs(uint16_t addr, uint16_t num, uint16_t* buffer)
{
    rt_uint8_t base = 0;
    rt_uint16_t value = 0;
    if ((0 <= addr) && (addr < HOLD_REG_MAX))
    {
        value = dev_rtu_aio_get_val(buffer, 0);
        //
        LOG_I("rtu->write reg addr:%d val:%d\n", addr, value);
        //
    }
    return num;
}
